package com.system.connect.springboot_flowers.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.system.connect.springboot_flowers.config.AlipayConfig;
import com.system.connect.springboot_flowers.dto.AlipayCreateDTO;
import com.system.connect.springboot_flowers.entity.Order;
import com.system.connect.springboot_flowers.service.AlipayService;
import com.system.connect.springboot_flowers.service.OrderService;
import com.system.connect.springboot_flowers.vo.AlipayQrCodeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@Service
public class AlipayServiceImpl implements AlipayService {
    
    @Autowired
    private AlipayClient alipayClient;
    
    @Autowired
    private AlipayConfig alipayConfig;
    
    @Autowired
    private OrderService orderService;
    
    @Override
    public AlipayQrCodeVO createQrCode(AlipayCreateDTO dto) {
        try {
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            
            // 设置异步通知地址
            request.setNotifyUrl(alipayConfig.getNotifyUrl());
            
            // 设置业务参数
            request.setBizContent("{" +
                "\"out_trade_no\":\"" + dto.getOrderId() + "\"," +
                "\"total_amount\":\"" + dto.getAmount() + "\"," +
                "\"subject\":\"" + dto.getSubject() + "\"," +
                "\"product_code\":\"FACE_TO_FACE_PAYMENT\"" +
                "}");
                
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            if(response.isSuccess()) {
                log.info("支付宝二维码生成成功，订单号：{}，二维码：{}", dto.getOrderId(), response.getQrCode());
                return AlipayQrCodeVO.builder()
                    .success(true)
                    .qrCode(response.getQrCode())
                    .outTradeNo(response.getOutTradeNo())
                    .build();
            }
            log.error("创建支付宝二维码失败：{}", response.getMsg());
            return AlipayQrCodeVO.builder()
                .success(false)
                .build();
        } catch (AlipayApiException e) {
            log.error("创建支付宝二维码异常", e);
            return AlipayQrCodeVO.builder()
                .success(false)
                .build();
        }
    }
    
    @Override
    @Transactional
    public void handleNotify(Map<String, String> params) {
        String tradeStatus = params.get("trade_status");
        String outTradeNo = params.get("out_trade_no");
        String tradeNo = params.get("trade_no");
        String totalAmount = params.get("total_amount");
        
        log.info("收到支付宝异步通知 - 订单号：{}，支付宝交易号：{}，交易状态：{}, 支付金额：{}", 
                outTradeNo, tradeNo, tradeStatus, totalAmount);
                
        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            try {
                // 查询订单是否已处理
                Order order = orderService.getByOrderNo(outTradeNo);
                if (order != null && order.getStatus() == 1) {
                    log.info("订单{}已处理，无需重复处理", outTradeNo);
                    return;
                }
                
                // 更新订单状态
                Order updateOrder = new Order();
                updateOrder.setOrderNo(outTradeNo);
                updateOrder.setStatus(1); // 1表示已支付
                updateOrder.setUpdatedTime(LocalDateTime.now());
                updateOrder.setPayAmount(new BigDecimal(totalAmount));
                updateOrder.setPayType(1); // 1表示支付宝支付
                
                orderService.updateById(updateOrder);
                log.info("订单{}支付成功，已更新订单状态", outTradeNo);
            } catch (Exception e) {
                log.error("处理支付成功通知时发生异常", e);
                throw new RuntimeException("处理支付成功通知失败", e);
            }
        }
    }
    
    @Override
    public Boolean checkPaymentStatus(String orderNo) {
        try {
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"" +
                "}");
                
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                String tradeStatus = response.getTradeStatus();
                log.info("订单{}的支付状态：{}", orderNo, tradeStatus);
                
                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    // 再次确认订单状态
                    Order order = orderService.getByOrderNo(orderNo);
                    if (order != null && order.getStatus() != 1) {
                        // 如果订单存在但未支付，更新订单状态
                        handleOrderPaymentSuccess(order, response.getTradeNo(), new BigDecimal(response.getTotalAmount()));
                    }
                    return true;
                }
            }
            log.error("查询支付状态失败：{}", response.getMsg());
            return false;
        } catch (AlipayApiException e) {
            log.error("查询支付状态异常", e);
            return false;
        }
    }
    
    @Transactional
    protected void handleOrderPaymentSuccess(Order order, String tradeNo, BigDecimal payAmount) {
        try {
            Order updateOrder = new Order();
            updateOrder.setId(order.getId());
            updateOrder.setStatus(1);
            updateOrder.setUpdatedTime(LocalDateTime.now());
            updateOrder.setPayAmount(payAmount);
            updateOrder.setPayType(1); // 1表示支付宝支付
            
            orderService.updateById(updateOrder);
            log.info("订单{}支付成功，已更新订单状态", order.getOrderNo());
        } catch (Exception e) {
            log.error("更新订单支付状态失败", e);
            throw new RuntimeException("更新订单支付状态失败", e);
        }
    }
} 